﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MkvSplicer.Video;

namespace MkvSplicer
{
    public partial class ProgressIndicator : Form
    {
        private FileInfo fileIn;
        public MkvHandler Handler {get; set;}

        public ProgressIndicator(FileInfo fileIn)
        {
            InitializeComponent();
            this.fileIn = fileIn;
            indexingWorker.RunWorkerAsync(fileIn);
        }

        private void indexingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            VideoTrack.UpdateProgress updater = (current, total, privdata) => {
                int percent = (int)(100.0 * ((double)current / (double)total));

                worker.ReportProgress(percent);
                if (worker.CancellationPending) {
                    e.Cancel = false;
                    return 1; //Signal a cancel to FFMS2
                }
                return 0;
            };

            MkvHandler handler = null;
            try
            {
                handler = new MkvHandler(e.Argument as FileInfo, updater, IntPtr.Zero);
            }
            catch (NotSupportedException ex)
            {
                e.Result = ex.Message;
            }

            if (handler != null)
                e.Result = handler;
        }

        private void indexingWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            indexingProgressBar.Value = e.ProgressPercentage;
        }

        private void indexingWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result is string)
            {
                string result = e.Result as string;
                if (!String.IsNullOrEmpty(result))
                {
                    MessageBox.Show(this, result, "Indexing failed",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                this.DialogResult = DialogResult.Cancel;
            }
            else if (e.Result is MkvHandler)
            {
                indexingProgressBar.Value = 100;
                this.Handler = e.Result as MkvHandler;
                this.DialogResult = DialogResult.OK;
            }

            this.Close();
        }

        private void ProgressIndicator_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (indexingWorker.IsBusy)
            {
                indexingWorker.CancelAsync();
                e.Cancel = true; //Wait for background worker to finish
            }
        }
    }
}
